import { isEmpty } from 'lodash';
import qs from 'qs';
import { SESSION_TIMEOUT } from './Const';
import Logger from './Logger';

let contextPath = '';

// 设置上下文
const setContextPath = (value) => {
    contextPath = value;
};

// 获取上下文
const getContextPath = () => contextPath;

const HEADERS = {
    'Content-Type': 'application/json; charset=UTF-8',
    'X-Requested-With': 'XMLHttpRequest',
};

// 自动补全上下文地址
const correctURL = (url) => {
    if (url.indexOf('http://') === -1 && url.indexOf('https://') === -1) {
        return contextPath + url;
    }
    return url;
};

const innerGet = ({ url, headers = {}, data = {} }) => {
    Logger.debug(data, url);
    const address = isEmpty(data) ? url : `${url}?${qs.stringify(data)}`;
    return fetch(correctURL(address), {
        method: 'GET',
        cache: 'no-cache',
        headers: { ...HEADERS, ...headers },
    }).then((response) => {
        // setTimeout(actions.app.endLoading, 168);
        if (response.headers.get('sessionstatus') === SESSION_TIMEOUT) {
            const login = response.headers.get('loginpath');
            return Promise.reject(new Error(`${SESSION_TIMEOUT}@${login}`));
        }
        return response.json();
    });
};

// GET请求
const get = (params) => {
    if (typeof params === 'string') return innerGet({ url: params });
    return innerGet(params);
};

// POST请求
const post = ({ url, headers = {}, data = {} }) => {
    Logger.debug(data, url);
    return fetch(correctURL(url), {
        method: 'POST',
        cache: 'no-cache',
        headers: { ...HEADERS, ...headers },
        body: JSON.stringify(data),
    }).then((response) => {
        // setTimeout(actions.app.endLoading, 168);
        if (response.headers.get('sessionstatus') === SESSION_TIMEOUT) {
            const login = response.headers.get('loginpath');
            return Promise.reject(new Error(`${SESSION_TIMEOUT}@${login}`));
        }
        return response.json();
    });
};

export default {
    setContextPath,
    getContextPath,
    get,
    post,
};
